package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.entity.QuartzTask;
import com.example.demo.mapper.QuartzTaskMapper;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class QuartzServiceImpl {
    @Autowired
    private Scheduler scheduler;
    
    @Autowired
    private QuartzTaskMapper quartzTaskMapper;

    // 添加任务
    public void addJob(QuartzTask quartzTask) throws SchedulerException {
        try {
            Class<?> clazz = Class.forName("com.example.demo.job."+quartzTask.getJobClassName());
            if (!Job.class.isAssignableFrom(clazz)) {
                throw new RuntimeException("指定的类必须实现 Job 接口");
            }
            @SuppressWarnings("unchecked")
            Class<? extends Job> jobClass = (Class<? extends Job>) clazz;
            
            JobDetail jobDetail = JobBuilder.newJob(jobClass)
                    .withIdentity(quartzTask.getTaskName(), quartzTask.getTaskGroup())
                    .build();
            
            // 创建Trigger
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(quartzTask.getTaskName() + "Trigger", quartzTask.getTaskGroup() + "TriggerGroup")
                    .withSchedule(CronScheduleBuilder.cronSchedule(quartzTask.getCronExpression()))
                    .build();
            
            // 保存到数据库
            quartzTask.setTaskStatus(1); // 设置为运行状态
            quartzTaskMapper.updateById(quartzTask);
            
            // 调度任务
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("找不到指定的Job类: " + quartzTask.getJobClassName());
        }
    }
    
    // 暂停任务
    public void pauseJob(String taskName, String taskGroup) throws SchedulerException {
        scheduler.pauseJob(JobKey.jobKey(taskName, taskGroup));
        
        // 更新数据库中的状态
        QuartzTask quartzTask = getTaskByName(taskName);
        if (quartzTask != null) {
            quartzTask.setTaskStatus(0);
            quartzTaskMapper.updateById(quartzTask);
        }
    }
    
    // 恢复任务
    public void resumeJob(String taskName, String taskGroup) throws SchedulerException {
        scheduler.resumeJob(JobKey.jobKey(taskName, taskGroup));
        
        // 更新数据库中的状态
        QuartzTask quartzTask = getTaskByName(taskName);
        if (quartzTask != null) {
            quartzTask.setTaskStatus(1);
            quartzTaskMapper.updateById(quartzTask);
        }
    }
    
    // 修改任务执行时间
    public void updateJobTime(String taskName, String taskGroup, String cronExpression) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(taskName + "Trigger", taskGroup + "TriggerGroup");
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
        trigger = trigger.getTriggerBuilder()
                .withIdentity(triggerKey)
                .withSchedule(scheduleBuilder)
                .build();
                
        scheduler.rescheduleJob(triggerKey, trigger);
        
        // 更新数据库中的cron表达式
        QuartzTask quartzTask = getTaskByName(taskName);
        if (quartzTask != null) {
            quartzTask.setCronExpression(cronExpression);
            quartzTaskMapper.updateById(quartzTask);
        }
    }
    
    // 删除任务
    public void deleteJob(String taskName, String taskGroup) throws SchedulerException {
        scheduler.deleteJob(JobKey.jobKey(taskName, taskGroup));
        
        // 从数据库中删除
        LambdaQueryWrapper<QuartzTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuartzTask::getTaskName, taskName);
        quartzTaskMapper.delete(wrapper);
    }
    
    // 根据任务名称获取任务
    private QuartzTask getTaskByName(String taskName) {
        LambdaQueryWrapper<QuartzTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuartzTask::getTaskName, taskName);
        return quartzTaskMapper.selectOne(wrapper);
    }
}